package cn.hinglo.gameclaw.data.utils;

import cn.hutool.core.util.StrUtil;
import lombok.Cleanup;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @createTime: 2017/12/29
 * @author: HingLo
 * @description: 字符串处理工具类
 */
public class CommonUtils {

    /**
     * 定义数组不是null，不是空白字符串
     *
     * @param str 待校验的字符串数组
     * @return boolean
     */
    public static boolean isNotBlank(String... str) {
        for (String s : str) {
            if (StrUtil.isBlank(s)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 通过图片的名称与类型组装访问图片的链接
     *
     * @param name 图片名称
     * @param type 图片类型
     * @return 完整的请求链接
     */
    public static String imgInstall(String name, int type) {
        return FieldUtils.URL + StrUtil.removePrefix(FileImageUtils.readUrlUtils(type), FileImageUtils.ROOT) + name;
    }

    /**
     * 获取用户的Ip地址
     *
     * @return
     */
    public static String getRemortIP(HttpServletRequest request) {
        String ip = request.getHeader("X-requested-For");
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StrUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String strIp : ips) {
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }

        return ip;
    }

    /**
     * 将文件保存到本地
     *
     * @param bfile
     * @param filePath
     * @param fileName
     * @return
     * @throws IOException
     */
    public static boolean convertInputStreamToFileUtils(byte[] bfile, String filePath, String fileName) throws IOException {
        try {
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
            }
            File file = new File(filePath + fileName);
            @Cleanup FileOutputStream fos = new FileOutputStream(file);
            @Cleanup BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 软件下载
     *
     * @param fileName 文件名称
     * @param filePath 文件路径
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */

    public static void downloadApkUtils(String fileName, String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File proposeFile = new File(filePath);
        long fSize = proposeFile.length();
        // 下载
        response.setContentType("application/x-download");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Length", String.valueOf(fSize));
        response.setHeader("Content-Disposition", "attachment; filename="
                + fileName);
        long pos = 0;
        if (null != request.getHeader("Range")) {
            // 断点续传
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            try {
                pos = Long.parseLong(request.getHeader("Range").replaceAll(
                        "bytes=", "").replaceAll("-", ""));
                response.setHeader("Content-Length", String.valueOf(fSize - pos));
            } catch (NumberFormatException e) {
                pos = 0;
            }
        }
        ServletOutputStream out = response.getOutputStream();
        BufferedOutputStream bufferOut = new BufferedOutputStream(out);
        InputStream inputStream = new FileInputStream(proposeFile);
        String contentRange = "bytes " +
                Long.toString(pos) + "-" +
                Long.toString(fSize - 1) + "/" +
                Long.toString(fSize);
        response.setHeader("Content-Range", contentRange);
        inputStream.skip(pos);
        byte[] buffer = new byte[5 * 1024];
        int length;
        while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
            bufferOut.write(buffer, 0, length);
        }
        bufferOut.flush();
        bufferOut.close();
        out.close();
        inputStream.close();
    }
}

